<?php
/*
 * @Author: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @Date: 2022-03-15 15:07:05
 * @LastEditors: 李红雨 - RainLee <rainlee1990@yeah.net>
 * @LastEditTime: 2022-04-14 13:42:39
 * @Description: File Description
 */

declare(strict_types=1);

namespace rainlee\auth\middleware;

use rainlee\auth\facade\Auth;

class Authenticate
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next, $guard = null)
    {
        $auth = Auth::guard($guard);
        $controller = array_map('parse_name', explode('.', $request->controller()));
        $node = implode(':', $controller) . ':' . parse_name($request->action());
        // 无需认证节点只接放行
        if ($auth->isIgnoredNode($node)) {
            return $next($request);
        }

        // 登录认证
        if (!$auth->check()) {
            return json([
                'errcode' => 4011,
                'message' => 'Unauthorized'
            ]);
        }

        // 权限认证
        if ($auth->authorization() && !$auth->authorization()->check($node, 'node')) {
            return json([
                'errcode' => 4014,
                'message' => 'NoAccess'
            ]);
        }

        return $next($request);
    }
}
